package com.zdp.provider.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zdp.provider.controller.CourseDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 类描述:
 *
 * @author ZhhengDP
 * @since 2021/8/18
 */
@Service
public class CourseService {

    private RestTemplate restTemplate;

    @Autowired
    public CourseService(RestTemplate restTemplate){
        this.restTemplate = restTemplate;
    }

    /**
     * @HystrixCommand 用于指定哪个方法需要进行容错保护
     * 属性 fallbackMethod 用于指定当方法发生异常时，用哪个方法来进行服务降级处理（方法替换）
     * 怎么就降个不停了？ ===> 因为自己的RestTemplate没有开启负载均衡却用服务名去调用服务
     * */
    @HystrixCommand(fallbackMethod = "loadCoursesFallBack")
    public List<CourseDto> loadCourses(Integer teacherId){
        // 使用服务名来进行服务的调用
        String url = "http://127.0.0.1:9907/course_info/courses?teacherId={teacherId}";
        HashMap<String,Object> param = new HashMap<>();
        param.put("teacherId",teacherId);
        List<CourseDto> result = restTemplate.getForObject(url, List.class, param);
        return result;

    }

    /**
     * 批量查询 老师的课程
     * @param teacherIds
     * @return
     */
    public List<List<CourseDto>> batchFindCourses(List<Integer> teacherIds){
        List<List<CourseDto>> result = new ArrayList<>();
        String url = "http://127.0.0.1:9907/course_info/courses?teacherId={teacherId}";
        HashMap<String,Object> param = new HashMap<>();
        for(Integer teacherId:teacherIds){
            param.put("teacherId",teacherId);
            List<CourseDto> courseDtoList = restTemplate.getForObject(url,List.class,param);
            result.add(courseDtoList);
        }
        return result;
    }

    protected List<CourseDto> loadCoursesFallBack(Integer teacherId){
        List<CourseDto> result = new ArrayList<>();
        CourseDto course1 = new CourseDto();
        CourseDto course2 = new CourseDto();
        course1.setContent("容错课程介绍1");
        course1.setName("容错课程1");
        course1.setTeacherId(teacherId);
        course1.setCourseServicePort(9906);
        /**====================================*/
        course2.setContent("容错课程介绍2");
        course2.setName("容错课程2");
        course2.setTeacherId(teacherId);
        course2.setCourseServicePort(9906);

        result.add(course1);
        result.add(course2);
        return result;
    }
}
